<?php

/**
 * AvatarForm form.
 *
 * @package    cpfaizenay
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: AvatarForm.class.php 20147 2009-07-13 11:46:57Z FabianLange $
 */
class AvatarForm extends BaseForm {

    public function configure() {

        $user = sfContext::getInstance()->getUser()->getGuardUser();

        $this->setWidget('file', new sfWidgetFormInputFileEditable(array(
            'label'     => 'Image',
            'file_src'    => $user->getAssetId() ? $user->getSfAsset()->getUrl('large') : '',
            'edit_mode'   => !is_null($user->getAssetId()),
            'is_image'    => !is_null($user->getAssetId()),
            'delete_label' => 'Supprimer',
            'template'  => '<div class="file_upload">%file%<br />%input%<br />%delete% %delete_label%</div>'
        )));
        $this->validatorSchema['file_delete'] = new sfValidatorPass();

        $this->setValidator('file', new sfValidatorFile(array(
            'mime_types' => 'web_images',
            'path' => sfConfig::get('app_sfAssetsLibrary_upload_dir', 'media'),
            'required' => false
        )));

        $this->widgetSchema->setFormFormatterName('list');
        $this->widgetSchema->setNameFormat('member_avatar[%s]');
   }

   public function save($con = null) {
//     if (null === $con){
//       $con = $this->getConnection();
//     }

     $folderParent = $this->createFolderParent($con);
     if($folderParent){
         $subFolder = $this->createSubFolder($folderParent, $con);
         if($subFolder){
           $this->createAsset($subFolder, $con);
         }
     }

     unset($this['file']);

//     return parent::save($con);
  }

  private function createAsset($folder, $con = null) {
     $file = $this->getValue('file');

     if($this->getValue('file_delete') == true || !empty($file)){
         $user = sfContext::getInstance()->getUser()->getGuardUser();
         
         // destroy old asset
         if($user->getAssetId()){
            $user->getSfAsset()->delete($con);
         }
     }

     if(!empty($file)) {
         $asset = new sfAsset();
         $asset->setFolderId($folder['id']);
         $asset->setFilename($file->getOriginalName());
         $asset->setAuthor(sfContext::getInstance()->getUser()->getGuardUser()->getId());
         $asset->setCopyright($this->getValue('copyright'));
         $asset->setDescription($file->getOriginalName());

         $options = array('thumbnails' => sfConfig::get('app_sfAssetsFile_avatar') );

         $asset->create($file->getTempName(), true, true, $options);
         $asset->save($con);

         // Mise a jour de asset_id de User
         $user->setAssetId($asset->getId());
         $user->save();
     }
  }

  private function createFolderParent($con = null) {
      // Création du dossier s'il n'existe pas
      $slug = 'media-avatar';
      $level = 1;
      $folder = Doctrine::getTable('sfAssetFolder')->getFolders($level, $slug)->fetchOne();

      if(!$folder){
          $folderName = 'Avatar';
          $mediaFolder = Doctrine::getTable('sfAssetFolder')->getFolders(0, 'media')->fetchOne();
          $folder = $this->createFolder($mediaFolder['id'], $folderName, $level);
      }

      return $folder;
  }

  private function createSubFolder($folderParent, $con = null){
      // Création du dossier s'il n'existe pas
      $slug = $folderParent['slug'] . '-' . date('Y') . '-' . date('m');
      $level = 2;
      $folder = Doctrine::getTable('sfAssetFolder')->getFolders($level, $slug)->fetchOne();

      if(!$folder){
          $folderName = date('Y') . '/' . date('m');
          $folder = $this->createFolder($folderParent['id'], $folderName, $level);
      }

      return $folder;
  }

  private function createFolder($id_folder, $folderName, $level = 1){
      $folder = new sfAssetFolder();
      $folder->setName($folderName);
      $folder->setLevel($level);

      $parent = sfAssetFolderTable::getInstance()->find($id_folder);
      $folder->getNode()->insertAsLastChildOf($parent);

      if($folder->create()){
        $folder->save($con);
      }

      return $folder;
  }
}
